<?php

namespace app\service;

use app\support\cache\Cache;

class TaskCacheService
{

    protected $taskId;

    /**
     * @param $taskId
     */
    public function __construct($taskId)
    {
        $this->taskId = $taskId;
    }

    /**
     * 生成一个新的实例
     * @param string $taskId
     * @return TaskCacheService
     */
    public static function make(string $taskId): TaskCacheService
    {
        return new TaskCacheService($taskId);
    }

    /**
     * 设置缓存数据
     * @param array $data
     * @return bool
     */
    public function set(array $data): bool
    {
        return Cache::set(
            $this->cacheKey(),
            $data,
            now()->addDay()
        );
    }

    /**
     * 合并数据
     * @param array $data
     * @return bool
     */
    public function merge(array $data): bool
    {
        $orgData = $this->get([]);

        $data = array_replace_recursive($orgData, $data);

        return $this->set($data);
    }

    /**
     * 获取缓存数据
     * @param array|null $default
     * @return array|null
     */
    public function get(array $default = null): ?array
    {
        return Cache::get($this->cacheKey(), $default);
    }

    /**
     * 获取缓存的Key
     * @return string
     */
    private function cacheKey(): string
    {
        return "task_" . $this->taskId;
    }
}
